﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.IO;
using System.Xml.Serialization;
using GestureService.Model;
using GestureService;

namespace GesturesService
{
    /// <summary>
    /// Summary description for WebService1
    /// </summary>
    //[WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]
    public class WebService1 : System.Web.Services.WebService
    {

        [WebMethod]
        public string HelloWorld(string name)
        {

            string root = Server.MapPath("~");
            if (!root.Substring(root.Length - 1, 1).Equals("\\"))
            {
                root += "\\";
            }
            root += "test" + DateTime.Now.Ticks + ".xml";
            string result = Server.HtmlDecode(name);
            result = "<?xml version=\"1.0\" encoding=\"utf-8\" ?> " + "\n" + result;
            //File.WriteAllText(root, result);
            saveMeasurement(parseXml(result));


            return "Hello World uspio, count = " + name.Length;
        }

        private measurement parseXml(string xml)
        {
            XmlSerializer s = new XmlSerializer(typeof(measurement));
            StringReader reader = new StringReader(xml);
            measurement novi = (measurement)s.Deserialize(reader);
            novi.pareseAfterXmlLoad();
            reader.Close();
            return novi;
        }

        private void saveMeasurement(measurement m)
        {
            using (var db = new DBContext())
            {
                db.Measurements.Add(m);
                db.SaveChanges();
            }
        }
    }
}
